﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using UtilZ.Dotnet.Ex.Base;

namespace UtilZ.Dotnet.Ex.DataStruct
{
    /// <summary>
    /// 定时任务管理器
    /// </summary>
    public class TimingTaskManager : IEnumerable<ITimingTask>, IDisposable
    {
        private static TimingTaskManager _default = null;
        /// <summary>
        /// 获取默认定时任务管理器
        /// </summary>
        public static TimingTaskManager Default
        {
            get
            {
                if (_default == null)
                {
                    _default = new TimingTaskManager();
                }

                return _default;
            }
        }


        private readonly ThreadEx _timerThread;
        private readonly AutoResetEvent _timerEvent = new AutoResetEvent(false);
        private readonly List<ITimingTask> _taskList = new List<ITimingTask>();
        private readonly object _lock = new object();
        private bool _disposed = false;

        /// <summary>
        /// 无参构造函数
        /// </summary>
        public TimingTaskManager()
        {
            this._timerThread = new ThreadEx(TimerThreadMethod);
        }

        /// <summary>
        /// 定时任务线程方法
        /// </summary>
        /// <param name="threadPara">线程参数</param>
        private void TimerThreadMethod(ThreadExPara threadPara)
        {
            try
            {
                ITimingTask timingTask = null;
                int delayMilliseconds;

                while (!threadPara.Token.IsCancellationRequested)
                {
                    for (int i = 0; i < this._taskList.Count;)
                    {
                        try
                        {
                            timingTask = this._taskList[i];
                            if (timingTask == null)
                            {
                                i++;
                                continue;
                            }

                            if (timingTask.HasExcute())
                            {
                                //当前任务可以执行,开始执行
                                timingTask.Excute();

                                if (this._taskList.Count > i && timingTask == this._taskList[i])
                                {
                                    //当前执行的任务和索引指定位置的任务匹配,说明外部没有移除当前执行的定时任务,索引+1
                                    if (timingTask.IsDone())
                                    {
                                        lock (this._lock)
                                        {
                                            this._taskList.RemoveAt(i);
                                        }
                                    }
                                    else
                                    {
                                        timingTask.UpdateExcuteTimestamp();
                                        i++;
                                    }
                                }
                                else
                                {
                                    //当前执行的任务和索引指定位置的任务不匹配,说明外部移除了当前执行的定时任务,索引不变
                                }
                            }
                            else
                            {
                                //当前任务不能可以执行,索引+1
                                i++;
                            }
                        }
                        catch (Exception exi)
                        {
                            if (timingTask == null)
                            {
                                ZLog.ZLoger.Error(exi, "定时任务执行异常");
                            }
                            else
                            {
                                ZLog.ZLoger.Error(exi, $"定时任务\"{timingTask.Name}\"执行异常");
                            }
                        }
                    }
                    timingTask = null;

                    lock (this._lock)
                    {
                        //如果有执行完成的任务,则从列表中移除
                        if (this._taskList.Count == 0)
                        {
                            //如果没有可执行的任务,则释放定时器
                            break;
                        }
                        else
                        {
                            //执行完成一次,再次更新下一次执行的延迟时间
                            delayMilliseconds = this.GetDelayMilliseconds();
                        }
                    }

                    if (delayMilliseconds <= 0)
                    {
                        continue;
                    }

                    try
                    {
                        if (this._timerEvent.WaitOne(delayMilliseconds))
                        {
                            if (this._disposed)
                            {
                                break;
                            }
                        }
                        else
                        {
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                ZLog.ZLoger.Error(ex);
            }
        }

        private int GetDelayMilliseconds()
        {
            long timestamp = TimeEx.GetTimestamp();
            long delayMilliseconds = long.MaxValue, temp;
            foreach (var task in this._taskList)
            {
                temp = task.GetNextExcuteWaitMilliseconds(timestamp);
                delayMilliseconds = Math.Min(delayMilliseconds, temp);
            }
            return (int)delayMilliseconds;
        }

        /// <summary>
        /// 添加一个定时任务
        /// </summary>
        /// <param name="timingTask">定时任务</param>
        public void AddTask(ITimingTask timingTask)
        {
            if (this._disposed)
            {
                ObjectEx.ThrowObjectDisposedException(this);
            }

            if (timingTask == null)
            {
                throw new ArgumentNullException(nameof(timingTask));
            }

            lock (this._lock)
            {
                if (this._taskList.Contains(timingTask))
                {
                    return;
                }

                this._taskList.Add(timingTask);
            }
            this.Start();
        }

        /// <summary>
        /// 添加多个定时任务
        /// </summary>
        /// <param name="timingTasks">定时任务集合</param>
        public void AddTask(IEnumerable<ITimingTask> timingTasks)
        {
            if (this._disposed)
            {
                ObjectEx.ThrowObjectDisposedException(this);
            }

            if (timingTasks != null)
            {
                bool addSucces = false;
                lock (this._lock)
                {
                    foreach (var timingTask in timingTasks)
                    {
                        if (timingTask != null)
                        {
                            this._taskList.Add(timingTask);
                            addSucces = true;
                        }
                    }
                }

                if (addSucces)
                {
                    this.Start();
                }
            }
        }

        /// <summary>
        /// 添加一个定时任务
        /// </summary>
        /// <param name="timingTask">定时任务</param>
        public void Remove(ITimingTask timingTask)
        {
            if (timingTask == null)
            {
                throw new ArgumentNullException(nameof(timingTask));
            }

            if (this._disposed)
            {
                ObjectEx.ThrowObjectDisposedException(this);
            }

            bool stop = false;
            lock (this._lock)
            {
                if (this._taskList.Remove(timingTask))
                {
                    if (this._taskList.Count == 0)
                    {
                        stop = true;
                    }
                }
                else
                {
                    return;
                }
            }

            if (stop)
            {
                this.Stop();
            }
        }

        /// <summary>
        /// 清空定时任务
        /// </summary>
        public void Clear()
        {
            lock (this._lock)
            {
                this._taskList.Clear();
            }

            this.Stop();
        }

        /// <summary>
        /// 启动定时任务
        /// </summary>
        public void Start()
        {
            if (this._disposed)
            {
                ObjectEx.ThrowObjectDisposedException(this);
            }

            lock (this._lock)
            {
                if (this._taskList.Count == 0)
                {
                    return;
                }

                this._timerThread.Start();

                try
                {
                    this._timerEvent.Set();
                }
                catch (ObjectDisposedException)
                {

                }
            }
        }

        /// <summary>
        /// 停止定时任务
        /// </summary>
        public void Stop()
        {
            if (this._disposed)
            {
                ObjectEx.ThrowObjectDisposedException(this);
            }

            lock (this._lock)
            {
                this._timerThread.Stop();

                try
                {
                    this._timerEvent.Set();
                }
                catch (ObjectDisposedException)
                {

                }
            }
        }




        /// <summary>
        /// Dispose
        /// </summary>
        public void Dispose()
        {
            try
            {
                if (this._disposed)
                {
                    return;
                }

                lock (this._lock)
                {
                    if (this._disposed)
                    {
                        return;
                    }

                    this._timerThread.Stop();
                    this._timerThread.Dispose();
                    this._timerEvent.Set();
                    this._timerEvent.Dispose();

                    this._disposed = true;
                }
            }
            catch (Exception ex)
            {
                ZLog.ZLoger.Error(ex);
            }
        }

        /// <summary>
        /// 执行枚举操作
        /// </summary>
        /// <returns>枚举器</returns>
        public IEnumerator<ITimingTask> GetEnumerator()
        {
            return this._taskList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

    }


}
